package org.sample.junit4.ex5;

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

import java.util.Objects;

/**
 * <b>自定义规则</b>
 * 重试规则，用于在测试失败时自动重试指定次数
 * 适用于需要多次尝试才能成功的测试场景
 */
public class RetryRule implements TestRule {
    private final int maxAttempts;

    public RetryRule(int maxAttempts) {
        this.maxAttempts = maxAttempts;
    }

    @Override
    public Statement apply(Statement base, Description desc) {
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                Throwable lastError = null;
                for (int i = 0; i < maxAttempts; i++) {
                    try {
                        base.evaluate();
                        return;  // 成功则退出
                    } catch (Throwable t) {
                        lastError = t;
                        System.err.printf("Test failed on attempt %d/%d%n", i + 1, maxAttempts);
                    }
                }

                throw Objects.requireNonNull(lastError);  // 所有尝试均失败
            }
        };
    }
}